package com.dbutils.dao;

import com.dbutils.entity.Account;
import com.dbutils.utils.JdbcKit;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.Connection;
import java.sql.SQLException;

public class AccountDAO {

    /**
     * 连接
     */
    private Connection conn;

    public AccountDAO() {
        this.conn = JdbcKit.getContainer().get();
    }


    /**
     * 查询账户ID
     *
     * @param id
     * @return
     */
    public Account findAccount(int id) {
        //处理事务 ，无参构造
        QueryRunner runner = new QueryRunner();
        String sql = "select * from account where id=?";
        Object[] params = {id};
        try {
            //附加连接 处理者为BeanHandler
            return (Account) runner.query(conn, sql, params, new
                    BeanHandler(Account.class));
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * 更新账户
     *
     * @param a
     */
    public void updateAccount(Account a) {
        QueryRunner runner = new QueryRunner();
        String sql = "update account set money=? where id=?";
        Object[] params = {a.getMoney(), a.getId()};
        try {
            runner.update(conn, sql, params);
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}

